package org.codetranslators.common;

import java.util.Vector;

public class UndirectedGraph {
	private int nodeCount;
	private Vector<Node> nodes; // nodes in this graph

	public UndirectedGraph(int size) {
		nodes = new Vector<Node>(size);
		//Initialize the nodes list with nulls
		for (int i = 0; i < size; i++) {
			nodes.addElement(null);
		}
	}

	public Vector<Node> nodes() {
		return nodes;
	}

	public Node newNode(String id) {
		Node node = new Node();
		node.setName(id);
		node.setPositionInGraph(nodeCount);
		return node;
	}


	public void addNode(Node n, int index){
		if(index != -1 && index < nodes.size())
			nodes.set(index, n);
		else
			nodes.addElement(n);
		incrementNodeCount();
	}


	/*
	public void addEdge(Node from, Node to) {
	    if (from.goesTo(to)) return;   // if there is already an edge, do not add one

	    to.addPredecessor(from);
	    from.addSuccessesor(to);
	}
	 */

	/*
	public boolean delete(Node node, Vector nodeList) {
		int numNodes = nodeList.size();
		Node nodeFound = null;
		for(int i = 0; i < numNodes; i++){
			nodeFound = (Node) nodeList.elementAt(i);
			if(nodeFound == node) break;
		}

		if(nodeFound != null){
			return nodeList.remove(nodeFound);
		}
		return false;
	 }

	 public boolean rmEdge(Node from, Node to) {
		 boolean b1 = delete(from, to.getPredecessors());
		 boolean b2 = delete(to, from.getSuccessors());
		 return b1 && b2;
	 }

	 */

	public int getNodeCount() {
		return nodeCount;
	}

	public void incrementNodeCount() {
		nodeCount++;
	}

	public void show(java.io.PrintStream out) {
		for (int i = 0; i < nodeCount; i++) {
			Node n = (Node) nodes.elementAt(i);
			out.print(n.toString());
			out.print(": ");

			// Print successors
			Vector succs = n.getSuccessors();
			int numSuccs = succs.size();
			for (int j = 0; j < numSuccs; j++) {
				Node succ = (Node) succs.elementAt(j);
				out.print(succ.toString());
				out.print(" ");
			}
			out.println();
		}
	}

	public Node getNode(int index) {
		return nodes.elementAt(index);
	}

	public Node nextNode(Node node)
	{
		int index = -1;
		for (int i = 0; i < nodeCount; i++)
		{
			Node n = nodes.elementAt(i);
			if (node == n)
			{
				index = i + 1;
				break;
			}
		}

		if (index == -1 || index == nodeCount)
			return null;
		return nodes.elementAt(index);
	}
}
